package day03.pm;

import javax.imageio.ImageIO;
import javax.swing.*;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.Random;

public class Demo01 {
    public static void main(String[] args) throws Exception {
        JFrame jFrame = new JFrame("捕鱼");
        jFrame.setSize(800,480);
        jFrame.setResizable(false);
        jFrame.setLocationRelativeTo(null);
        jFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        Pool pool = new Pool();
        jFrame.add(pool);
        jFrame.setVisible(true);
        pool.move();
    }
}//Demo02结束

//Pool开始
class Pool extends JPanel{
    BufferedImage bg ;//定义背景图
    Fish[] fish;//声明一个鱼的数组
    public Pool() throws IOException {
        bg = ImageIO.read(new File("fish/images/bg.jpg"));
        fish = new Fish[9+9+9+2];//创建鱼数组
        for(int i=0;i<9;i++){//循环创建鱼对象
            fish[i] = new Fish("fish0"+(i+1));
            fish[i+9]=new Fish("fish0"+(i+1));
            fish[i+9+9]= new Fish("fish0"+(i+1));
        }
        fish[fish.length-2] = new Fish("fish13");
        fish[fish.length-1] = new Fish("fish14");
    }
    public void paint(Graphics g) {
        g.drawImage(bg,0,0,null);
        for(int i=0;i<fish.length;i++){//将鱼数组中的所有鱼绘制出来
            g.drawImage(fish[i].image,fish[i].x,fish[i].y,null);
        }
    }

    /**
     * 鱼游动的方法
     */
    public void move() throws InterruptedException {
        while (true){
            for(int i=0;i<fish.length;i++){
                fish[i].x--;
                if(fish[i].x<-fish[i].width){
                    fish[i].x = 800;
                }
            }
            Thread.sleep(10);//休眠10毫秒
            repaint();//重画
        }
    }
}//Pool结束

//Fish开始
class Fish{
    BufferedImage image;//图片
    int width;//鱼图片的宽
    int height;//鱼图片的高
    int x; //x坐标
    int y; //y坐标
    
    public Fish(String name) throws IOException {
        String str = "fish/images/"+name+"_00.png";
        System.out.println(str);
        image = ImageIO.read(
                new File(str));
        width = image.getWidth();
        height = image.getHeight();
        Random r = new Random();
        x = r.nextInt(800-width);
        y = r.nextInt(480-height);
    }

}
//Fish结束
